#include "hisdataui.h"
#include "ui_hisdataui.h"
#include "constants.h"
#include "sqlite3.h"
#include "log4z.h"
#include <QTimer>
#include <QDateTime>
#include <QScrollBar>

//Update result
static int HisResult(void *pUserData, int argc, char **argv, char **azColName)
{
    QStringList qsl;
    for (int i=0; i<argc; i++)
    {
        LOGFMTD("Result push one data");
        qsl.push_back(argv[i]?argv[i]:"NULL");
    }
    HisDataUI* hisUI = (HisDataUI*)pUserData;
    if (0 != hisUI)
    {
        hisUI->updateHisData(qsl);
    }
    return 0;
}

HisDataUI::HisDataUI(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HisDataUI),
    dataModel(new QStandardItemModel()),
    iRow(0)
{
    ui->setupUi(this);
    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint );
    //load logo and background
    QPixmap lg(logoStr);
    ui->logo->setPixmap(lg);
    QPixmap bg(backgroundStr);
    QPalette background;
    background.setBrush(QPalette::Background, QBrush(bg));
    setPalette(background);
//    QPalette palette = ui->data->palette();
//    palette.setColor(backgroundRole(), QColor(255,255,255));
//    ui->data->setPalette(palette);
//    ui->data->setAutoFillBackground(true);
    //set font color
    QPalette pe;
    pe.setColor(QPalette::WindowText,Qt::white);
    ui->cTime->setPalette(pe);
    ui->title->setPalette(pe);
    //button style
    ui->btnRet->setStyleSheet(redBtn);
    ui->btnSrh->setStyleSheet(blueBtn);
    ui->btnExport->setStyleSheet(greenBtn);
    QPalette btnPe;
    btnPe.setColor(QPalette::ButtonText,Qt::white);
    ui->btnRet->setPalette(btnPe);
    ui->btnSrh->setPalette(btnPe);
    ui->btnExport->setPalette(btnPe);
    //Combo box
    ui->stYr->setStyleSheet("QScrollBar::vertical {width: 30px;}");
    ui->edYr->setStyleSheet("QScrollBar::vertical {width: 30px;}");
    ui->stMth->setStyleSheet("QScrollBar::vertical {width: 35px;}");
    ui->edMth->setStyleSheet("QScrollBar::vertical {width: 35px;}");
    ui->stDy->setStyleSheet("QScrollBar::vertical {width: 35px;}");
    ui->edDy->setStyleSheet("QScrollBar::vertical {width: 35px;}");

    btnPe.setColor(QPalette::ButtonText, Qt::white);
    ui->btnRet->setStyleSheet(blueBtn);
    ui->btn0->setStyleSheet(blueBtn);
    ui->btn1->setStyleSheet(blueBtn);
    ui->btn2->setStyleSheet(blueBtn);
    ui->btn3->setStyleSheet(blueBtn);
    ui->btn4->setStyleSheet(blueBtn);
    ui->btn5->setStyleSheet(blueBtn);
    ui->btn6->setStyleSheet(blueBtn);
    ui->btn7->setStyleSheet(blueBtn);
    ui->btn8->setStyleSheet(blueBtn);
    ui->btn9->setStyleSheet(blueBtn);
    ui->btnC->setStyleSheet(blueBtn);

    ui->btn0->setPalette(btnPe);
    ui->btn1->setPalette(btnPe);
    ui->btn2->setPalette(btnPe);
    ui->btn3->setPalette(btnPe);
    ui->btn4->setPalette(btnPe);
    ui->btn5->setPalette(btnPe);
    ui->btn6->setPalette(btnPe);
    ui->btn7->setPalette(btnPe);
    ui->btn8->setPalette(btnPe);
    ui->btn9->setPalette(btnPe);
    ui->btnC->setPalette(btnPe);
    ui->btnC->setIcon(QIcon(delStr));
    ui->btnC->setIconSize(QSize(20, 10));
    //Spinbox
//    ui->stYr->setStyleSheet("QSpinBox { border: 1px outset grey;padding-right: 20px;}"
//                          "QSpinBox::up-button {subcontrol-position: right; right: 20px; width: 20px; height:29px;}"
//                          "QSpinBox::down-button {subcontrol-position: right; width: 20px; height:29px;}");
//    ui->edYr->setStyleSheet("QSpinBox { border: 1px outset grey;padding-right: 20px;}"
//                          "QSpinBox::up-button {subcontrol-position: right; right: 20px; width: 20px; height:29px;}"
//                          "QSpinBox::down-button {subcontrol-position: right; width: 20px; height:29px;}");
//    ui->stMth->setStyleSheet("QSpinBox { border: 1px outset grey;padding-right: 20px;}"
//                          "QSpinBox::up-button {subcontrol-position: right; right: 20px; width: 20px; height:29px;}"
//                          "QSpinBox::down-button {subcontrol-position: right; width: 20px; height:29px;}");
//    ui->edMth->setStyleSheet("QSpinBox { border: 1px outset grey;padding-right: 20px;}"
//                          "QSpinBox::up-button {subcontrol-position: right; right: 20px; width: 20px; height:29px;}"
//                          "QSpinBox::down-button {subcontrol-position: right; width: 20px; height:29px;}");
//    ui->stDy->setStyleSheet("QSpinBox { border: 1px outset grey;padding-right: 20px;}"
//                          "QSpinBox::up-button {subcontrol-position: right; right: 20px; width: 20px; height:29px;}"
//                          "QSpinBox::down-button {subcontrol-position: right; width: 20px; height:29px;}");
//    ui->edDy->setStyleSheet("QSpinBox { border: 1px outset grey;padding-right: 20px;}"
//                          "QSpinBox::up-button {subcontrol-position: right; right: 20px; width: 20px; height:29px;}"
//                          "QSpinBox::down-button {subcontrol-position: right; width: 20px; height:29px;}");
    //Combo box
    QStringList yearLst;
    for (int i=0; i<100; i++)
    {
        yearLst << QString("%0").arg(i+2015);
    }
    ui->stYr->addItems(yearLst);
    ui->edYr->addItems(yearLst);
    //month
    QStringList monthLst;
    for (int i=1; i<=12; i++)
    {
        monthLst << QString("%0").arg(i);
    }
    ui->stMth->addItems(monthLst);
    ui->edMth->addItems(monthLst);
    //day
    QStringList dayLst;
    for (int i=1; i<=31; i++)
    {
        dayLst << QString("%0").arg(i);
    }
    ui->stDy->addItems(dayLst);
    ui->edDy->addItems(dayLst);
    //Fill in day
    QDateTime curTime = QDateTime::currentDateTime();
    ui->stYr->setCurrentText(QString("%1").arg(curTime.date().year()));
    ui->edYr->setCurrentText(QString("%1").arg(curTime.date().year()));
    ui->stMth->setCurrentText(QString("%1").arg(curTime.date().month()));
    ui->edMth->setCurrentText(QString("%1").arg(curTime.date().month()));
    ui->stDy->setCurrentText(QString("%1").arg(curTime.date().day()));
    ui->edDy->setCurrentText(QString("%1").arg(curTime.date().day()));

    //Table
    dataModel->setColumnCount(7);
//    dataModel->setHeaderData(0, Qt::Horizontal, "No");
//    dataModel->setHeaderData(1, Qt::Horizontal, "电压");
//    dataModel->setHeaderData(2, Qt::Horizontal, "脉宽");
//    dataModel->setHeaderData(3, Qt::Horizontal, "次数");
//    dataModel->setHeaderData(4, Qt::Horizontal, "间隔");
//    dataModel->setHeaderData(5, Qt::Horizontal, "流速");
//    dataModel->setHeaderData(6, Qt::Horizontal, "时间");
    dataModel->setHorizontalHeaderItem(0, new QStandardItem(tr("Name")));
    dataModel->setHorizontalHeaderItem(1, new QStandardItem(tr("ID")));
    dataModel->setHorizontalHeaderItem(2, new QStandardItem(tr("Cell")));
    dataModel->setHorizontalHeaderItem(3, new QStandardItem(tr("Barcode")));
    dataModel->setHorizontalHeaderItem(4, new QStandardItem(tr("Voltage")));
    dataModel->setHorizontalHeaderItem(5, new QStandardItem(tr("Pulse width")));
    dataModel->setHorizontalHeaderItem(6, new QStandardItem(tr("Repetition")));
    dataModel->setHorizontalHeaderItem(7, new QStandardItem(tr("Interval")));
    dataModel->setHorizontalHeaderItem(8, new QStandardItem(tr("Velocity")));
    dataModel->setHorizontalHeaderItem(9, new QStandardItem(tr("Shake")));
    dataModel->setHorizontalHeaderItem(10, new QStandardItem(tr("Time")));
    ui->hisTable->setModel(dataModel);
    //Set fixed header
    ui->hisTable->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(5, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(6, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(7, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(8, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(9, QHeaderView::Fixed);
    ui->hisTable->horizontalHeader()->setSectionResizeMode(10, QHeaderView::Fixed);
    //Set width
    ui->hisTable->setColumnWidth(0, 90);
    ui->hisTable->setColumnWidth(1, 100);
    ui->hisTable->setColumnWidth(2, 90);
    ui->hisTable->setColumnWidth(3, 90);
    ui->hisTable->setColumnWidth(4, 90);
    ui->hisTable->setColumnWidth(5, 110);
    ui->hisTable->setColumnWidth(6, 90);
    ui->hisTable->setColumnWidth(7, 80);
    ui->hisTable->setColumnWidth(8, 80);
    ui->hisTable->setColumnWidth(9, 60);
    ui->hisTable->setColumnWidth(10, 140);
    ui->hisTable->verticalHeader()->hide();
    ui->hisTable->verticalScrollBar()->setStyleSheet("QScrollBar::vertical {width: 40px;}");

    QTimer *upTime = new QTimer(this);
    connect(upTime, SIGNAL(timeout()), this, SLOT(updateTime()));
    updateTime();
    upTime->start(1000);
    connect(this, SIGNAL(updateHisData(QStringList)), this, SLOT(showHisData(QStringList)));
}

HisDataUI::~HisDataUI()
{
    delete ui;
}

void HisDataUI::updateTime()
{
    QDateTime curTime = QDateTime::currentDateTime();
    QString lblTm = curTime.date().toString("yyyy/MM/dd") + "\n " + curTime.time().toString("hh:mm:ss");
    this->ui->cTime->setText(lblTm);
}

void HisDataUI::getShow()
{
    this->show();
    this->activateWindow();
    this->raise();
}

void HisDataUI::on_btnRet_clicked()
{
    this->hide();
    emit retMain();
}

void HisDataUI::on_btnSrh_clicked()
{
    QDate qdSt, qdEd;
    qdSt.setDate(ui->stYr->currentText().toInt(),
                 ui->stMth->currentText().toInt(),
                 ui->stDy->currentText().toInt());
    qdEd.setDate(ui->edYr->currentText().toInt(),
                 ui->edMth->currentText().toInt(),
                 ui->edDy->currentText().toInt());
    //use sqlite
    sqlite3 * pDB = 0;
    iRow = 0;
    dataModel->removeRows(0, dataModel->rowCount());
    int nRes = sqlite3_open(dbPath.toStdString().c_str(), &pDB);

    if (ui->lneCode->text().length() == 0)
    {
        LOGFMTD("Use time to query the data!");
        char* cErrMsg;
        QString qsQuery = "select * from hisData where DATETIME(hisData.tm) <='";
        qsQuery += qdEd.toString("yyyy-MM-dd");
        qsQuery += " 23:59:59' and DATETIME(hisData.tm) >='";
        qsQuery += qdSt.toString("yyyy-MM-dd");
        qsQuery += "';";

        nRes = sqlite3_exec(pDB, qsQuery.toStdString().c_str(), HisResult, this, &cErrMsg);
    } else {
        LOGFMTD("Use barcode to query the data!");
        char* cErrMsg;
        QString qsQuery = "select * from hisData where hisData.barcd =='";
        qsQuery += ui->lneCode->text();
        qsQuery += "';";

        nRes = sqlite3_exec(pDB, qsQuery.toStdString().c_str(), HisResult, this, &cErrMsg);
    }
    //close
    sqlite3_close(pDB);
}

void HisDataUI::on_btnExport_clicked()
{
    //check /dev/sdb

    //mount /dev/sdb

    //export data to one file

}

void HisDataUI::showHisData(QStringList qslData)
{
    //QStringList qslData = qData.split(':');
    int iSz = qslData.size();
    LOGFMTD("Update his data with size=%d", iSz);

    int iLpRow = iRow++;
    QStandardItem *qiNa = new QStandardItem(qslData.at(7));
    qiNa->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 0, qiNa);

    QStandardItem *qiID = new QStandardItem(qslData.at(8));
    qiID->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 1, qiID);

    QStandardItem *qiCell = new QStandardItem(qslData.at(9));
    qiCell->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 2, qiCell);

    QStandardItem *qiBar = new QStandardItem(qslData.at(10));
    qiBar->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 3, qiBar);

    QStandardItem *qiDianya = new QStandardItem(qslData.at(1));
    qiDianya->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 4, qiDianya);

    QStandardItem *qiMaikuan = new QStandardItem(qslData.at(2));
    qiMaikuan->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 5, qiMaikuan);

    QStandardItem *qiCishu = new QStandardItem(qslData.at(3));
    qiCishu->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 6, qiCishu);

    QStandardItem *qiJiange = new QStandardItem(qslData.at(4));
    qiJiange->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 7, qiJiange);

    QStandardItem *qiLiusu = new QStandardItem(qslData.at(5));
    qiLiusu->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 8, qiLiusu);

    QStandardItem *qiShake = new QStandardItem(qslData.at(6));
    qiShake->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 9, qiShake);

    QString qstrTm = qslData.at(0);
    QStandardItem *qiTm = new QStandardItem(qstrTm.left(10));
    qiTm->setTextAlignment(Qt::AlignCenter);
    dataModel->setItem(iLpRow, 10, qiTm);
}

void HisDataUI::on_btn0_clicked()
{
    ui->lneCode->insert("0");
}

void HisDataUI::on_btn1_clicked()
{
    ui->lneCode->insert("1");
}

void HisDataUI::on_btn2_clicked()
{
    ui->lneCode->insert("2");
}

void HisDataUI::on_btn3_clicked()
{
    ui->lneCode->insert("3");
}

void HisDataUI::on_btn4_clicked()
{
    ui->lneCode->insert("4");
}

void HisDataUI::on_btn5_clicked()
{
    ui->lneCode->insert("5");
}

void HisDataUI::on_btn6_clicked()
{
    ui->lneCode->insert("6");
}

void HisDataUI::on_btn7_clicked()
{
    ui->lneCode->insert("7");
}

void HisDataUI::on_btn8_clicked()
{
    ui->lneCode->insert("8");
}

void HisDataUI::on_btn9_clicked()
{
    ui->lneCode->insert("9");
}

void HisDataUI::on_btnC_clicked()
{
    ui->lneCode->setText("");
}
